//
//  RebateVC.swift
//  kxf
//   收益详情
//  Created by Mac on 2024/3/11.
//  

import Foundation
import UIKit
import MCToast
import MJRefresh

class RebateVC : WHBaseViewVC {
    
    var accountDict = NSDictionary()
    var dataSourceArray = NSMutableArray()
    
    var serviceType = 1
    var serviceName = "交易分润"
    var pageNum = 1
    var pageSize = 5
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        sendAccountDetailRequest()
//        sendAccountListRequest()
        sendTypeRequest()
    }
    lazy var withdrawListBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("提现记录", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        
        btn.addTarget(self, action: #selector(recordListAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var topVm : RebateTopVM = {
        let vm = RebateTopVM.init(frame: CGRect.init(x: 0, y: kFitWidth(0), width: SCREEN_WIDHT, height: 0))
        
        vm.withDrawBlock = {()in
            let vc = WithDrawVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        return vm
    }()
    lazy var tradeRebateVm : RebateTradeDataVM = {
        let vm = RebateTradeDataVM.init(frame: CGRect.init(x: 0, y: kFitWidth(0), width: 0, height: 0))
        vm.titleVm.tapBlock = {()in
            self.showTypeAlertSheet()
        }
        return vm
    }()
    
    lazy var tableView : UITableView = {
        let vi = UITableView.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(1), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(getNavigationBarHeight()+kFitWidth(1))), style: .plain)
        vi.delegate = self
        vi.dataSource = self
        vi.separatorStyle = .none
        vi.backgroundColor = .COLOR_LIGHT_GREY
        
        vi.register(RebateTableViewCell.classForCoder(), forCellReuseIdentifier: "RebateTableViewCell")
        
        if #available(iOS 11.0, *) {
            vi.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        vi.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.pageNum = 1
            self.sendAccountListRequest()
        })

        vi.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            self.pageNum += 1
            self.sendAccountListRequest()
        })
        return vi
    }()
    lazy var emptyView : EmptyViewWithBtn = {
        let emptyViewT = EmptyViewWithBtn.init(frame: CGRect.zero)
        emptyViewT.isHidden = true
        emptyViewT.contentLabel.text = "还没有记录~"
        
        return emptyViewT
    }()
    lazy var typeDataArray : NSArray = {
        return [["service_type":1,"service_type_name":"交易分润"],
                ["service_type":91,"service_type_name":"感恩奖"]]
    }()
}

extension RebateVC{
    @objc func recordListAction() {
        let vc = WithDrawListVC()
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension RebateVC{
    func initUI() {
        initNavi(titleStr: "钱包")
        self.navigationView.addSubview(withdrawListBtn)
        view.backgroundColor = .COLOR_LIGHT_GREY
//        view.addSubview(topVm)
//        view.addSubview(tradeRebateVm)
        
        view.addSubview(tableView)
        tableView.tableHeaderView = topVm
        tableView.addSubview(emptyView)
        emptyView.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: (self.tableView.frame.height-topVm.selfHeight-tradeRebateVm.selfHeight)*0.5+topVm.selfHeight+tradeRebateVm.selfHeight+kFitWidth(20))
        
        setConstrait()
    }
    func setConstrait() {
        withdrawListBtn.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.centerY.lessThanOrEqualTo(self.naviTitleLabel)
            make.width.equalTo(kFitWidth(72))
            make.height.equalTo(self.naviTitleLabel)
        }
    }
    func showTypeAlertSheet() {
        let alertVc = UIAlertController(title: "请选择收益类型", message: "", preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler:nil)
        alertVc.addAction(cancelAction)
        
        for i in 0..<typeDataArray.count{
            let dict = typeDataArray[i]as? NSDictionary ?? [:]
            let action = UIAlertAction(title: "\(dict["service_type_name"]as! String)", style: .default) { ac in
                DLLog(message: "\(dict)")
                self.serviceName = "\(dict["service_type_name"]as! String)"
                self.tradeRebateVm.titleVm.titleLabel.text = self.serviceName
                self.tradeRebateVm.tipsLabel.text = "\(self.serviceName)-收入总金额"
                
                self.serviceType = dict["service_type"]as? Int ?? 1
                self.pageNum = 1
                self.sendAccountListRequest()
            }
            alertVc.addAction(action)
        }
        
        self.present(alertVc, animated:true, completion:nil)
    }
    func updateUI() {
        if self.typeDataArray.count > 0 {
            let dict = self.typeDataArray.firstObject as? NSDictionary ?? [:]
            serviceType = dict["service_type"]as? Int ?? 1
            serviceName = dict["service_type_name"]as? String ?? "交易分润"
            
            sendAccountListRequest()
        }
        
    }
}

extension RebateVC:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        if section == 0{
//            return 0
//        }else{
            emptyView.isHidden = dataSourceArray.count > 0 ? true : false
            return dataSourceArray.count
//        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RebateTableViewCell") as! RebateTableViewCell
        
        let dict = self.dataSourceArray[indexPath.row] as? NSDictionary ?? [:]
        cell.updateUI(dict: dict)
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kFitWidth(142)
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        if section == 0 {
//            return topVm
//        }else{
            return tradeRebateVm
//        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        if section == 0 {
//            return topVm.selfHeight
//        }else{
            return tradeRebateVm.selfHeight + kFitWidth(10)
//        }
    }
}

extension RebateVC{
    func sendAccountDetailRequest(){
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: URL_account_wallet) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            if responseObject["code"]as? Int ?? 0 == 200 {
                self.accountDict = responseObject["data"]as? NSDictionary ?? [:]
                self.topVm.updateUI(dict: self.accountDict)
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "")", viewController: self)
            }
        }
    }
    func sendAccountListRequest(){
        MCToast.mc_loading()
        let urlString = "\(URL_getUserWallet_list)?serviceType=\(serviceType)&pageNum=\(pageNum)&pageSize=\(pageSize)"
        WHNetworkUtil.shareManager().GET(urlString: urlString) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            if responseObject["code"]as? Int ?? 0 == 200 {
                self.tableView.mj_footer!.endRefreshing()
                self.tableView.mj_header!.endRefreshing()
                
                let dataDict = responseObject["data"]as? NSDictionary ?? [:]
                let dataArr = dataDict["list"]as? NSArray ?? []
                
                if self.pageNum == 1{
                    self.dataSourceArray.removeAllObjects()
                }
                // 提示没有更多数据
                if dataArr.count < self.pageSize {
                    self.tableView.mj_footer!.endRefreshingWithNoMoreData()
                }
                
                self.dataSourceArray.addObjects(from: dataArr as! [Any])
                self.tableView.reloadData()
                
                self.tradeRebateVm.moneyLabel.text = "\(dataDict["obj"]as? Double ?? 0.00)"
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "")", viewController: self)
            }
        }
    }
    func sendTypeRequest(){
        WHNetworkUtil.shareManager().GET(urlString: URL_account_wallet_list) { responseObject in
            DLLog(message: "sendTypeRequest:\(responseObject)")
            
            if responseObject["code"]as? Int ?? 0 == 200{
                let dataObj = responseObject["data"]as? NSDictionary ?? [:]
                let list = dataObj["list"]as? NSArray ?? []
                self.typeDataArray = list
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "网络异常，请稍后重试")", viewController: self)
            }
            self.updateUI()
        }
    }
}
